package com.example.fivechessonline;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.graphics.Color;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TimeUtils;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextClock;
import android.widget.TextView;

import com.google.gson.Gson;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Request;
import okhttp3.Response;

public class ChessActivity2 extends AppCompatActivity {
    private int tableId;
    private final static String TAG=MainActivity.class.getName();
    private Runnable updaterunnable;
    private transient boolean stopFlag = false;
    private StepTurn stepTurn;
    private String BlackOrWhite;
    private enum  StepTurn {
        BLACK{
            @NonNull
            @Override
            public String toString() {
                return "black";
            }
            public int chessDrawID(){
                return R.drawable.black;
            }
        },WHITE{
            @NonNull
            @Override
            public String toString(){
                return "white";
            }
            public int chessDrawID(){
                return R.drawable.white;
            }
        },NONE;
        public int chessDrawID(){
            return 0;
        }
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chess2);
        this.tableId=getIntent().getIntExtra("tableId",0);
        this.BlackOrWhite=getIntent().getStringExtra("blackOrWhite");
        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        LinearLayout.LayoutParams tableContainerLayoutParams = new LinearLayout.LayoutParams(metrics.widthPixels,metrics.widthPixels);
        ((FrameLayout)findViewById(R.id.tableContainer)).setLayoutParams(tableContainerLayoutParams);
        LinearLayout chessButtons=findViewById(R.id.chessButton);
        for (int i=0;i<9;i++){
            LinearLayout oneLine = new LinearLayout(this);
            for (int j=0;j<9;j++){
                Button button = new Button(this);
                LinearLayout.LayoutParams layoutParams= new LinearLayout.LayoutParams(metrics.widthPixels/9,metrics.widthPixels/9);
                button.setLayoutParams(layoutParams);
                button.setBackgroundColor(Color.TRANSPARENT);
                final int finali=i;
                final int finalj=j;
                button.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if(stepTurn.toString().equals(BlackOrWhite)){
                            button.setBackground(ActivityCompat.getDrawable(getApplicationContext(),stepTurn.chessDrawID()));
                            String url ="https://fivechess.tzchenyu.com/walk/"+tableId+"/"+finalj+"/"+finali;
                            Request request = new Request.Builder().url(url).build();
                            MainActivity.client.newCall(request).enqueue(new Callback() {
                                @Override
                                public void onFailure(@NonNull Call call, @NonNull IOException e) {
                                    Log.i(TAG,"onFailure"+ call.toString(),e);
                                }

                                @Override
                                public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {

                                }
                            });
                            stepTurn=StepTurn.NONE;
                        }

                    }
                });
                oneLine.addView(button);
            }
            chessButtons.addView(oneLine);
        }
        updaterunnable = new Runnable() {
            @Override
            public void run() {
                while(!stopFlag){
                    String url ="https://fivechess.tzchenyu.com/table_status/"+tableId;
                    Request request = new Request.Builder().url(url).build();
                    MainActivity.client.newCall(request).enqueue(new Callback() {
                        @Override
                        public void onFailure(@NonNull Call call, @NonNull IOException e) {

                        }

                        @Override
                        public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                            String content = response.body().string();
                            Gson gson = new Gson();
                            Map<String,Object> result = gson.fromJson(content,Map.class);
                            Log.i(TAG,content);
                            Log.i(TAG,"onResponse:"+result.get("table"));
                            final Map<String,Object> tableInfo = (Map<String,Object>) result.get("table");
                            Runnable runnable = new Runnable() {
                                public void run() {
                                    if(tableInfo.get("black_user_info")!=null){
                                        Map<String,Object> blackUserInfo = (Map<String,Object>) tableInfo.get("black_user_info");
                                        String balckUserName =(String) blackUserInfo.get("name");
                                        ((TextView) findViewById(R.id.userBlack)).setText(balckUserName);
                                    }
                                    if(tableInfo.get("white_user_info")!=null){
                                        Map<String,Object> whiteUserInfo = (Map<String,Object>) tableInfo.get("white_user_info");
                                        String whiteUserName =(String) whiteUserInfo.get("name");
                                        ((TextView) findViewById(R.id.userWhite)).setText(whiteUserName);
                                    }
                                    if (result.get("game")!=null) {
                                        Map<String, Object> gameInfo =  (Map<String,Object>) result.get("game");
                                        String next= (String) gameInfo.get("next");
                                        if("black".equals(next)){
                                            stepTurn=StepTurn.BLACK;
                                            ((TextView)findViewById(R.id.tableStatus)).setText("黑棋走子");
                                        }else if("white".equals(next)){
                                            stepTurn=StepTurn.WHITE;
                                            ((TextView)findViewById(R.id.tableStatus)).setText("白棋走子");
                                        }
                                        if(gameInfo.get("winner")!=null){
                                            String winner = (String) gameInfo.get("winner");
                                            ((TextView)findViewById(R.id.tableStatus)).setText("棋局结束，胜者为："+winner);
                                            stepTurn = StepTurn.NONE;
                                        }
                                    }
                                    if(result.get("steps")!=null){
                                        List<Map<String,Object>> steps = (List<Map<String,Object>>) result.get("steps");
                                        for (Map<String,Object> step:steps){
                                            int stepNum =(int)(double) step.get("step_num");
                                            int x =(int) (double)step.get("x");
                                            int y =(int) (double)step.get("y");
                                            LinearLayout oneLine = (LinearLayout) ((LinearLayout)findViewById(R.id.chessButton)).getChildAt(y);
                                            Button chess = (Button) oneLine.getChildAt(x);
                                            if(stepNum %2==1){
                                                chess.setBackground(ActivityCompat.getDrawable(getApplicationContext(),StepTurn.BLACK.chessDrawID()));
                                            }else{
                                                chess.setBackground(ActivityCompat.getDrawable(getApplicationContext(),StepTurn.WHITE.chessDrawID()));
                                            }
                                        }
                                    }
                                }
                            };
                            runOnUiThread(runnable);

                        }
                    });
                    try {
                        TimeUnit.SECONDS.sleep(1);
                    }catch (InterruptedException e){
                        e.printStackTrace();
                    }

                }
            }
        };

    }

    @Override
    protected void onResume() {
        super.onResume();
        stopFlag= false;
        new Thread(updaterunnable).start();
    }

    @Override
    protected void onPause() {
        super.onPause();
        stopFlag = true;

    }



    public void leaveTable(View view){
        String url ="https://fivechess.tzchenyu.com/leave_table/"+tableId;

        Request request = new Request.Builder().url(url).build();
        MainActivity.client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {

            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                finish();
            }
        });

    }

}